package com.cinorecycle.utils;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.http.HttpUtil;
import lombok.extern.slf4j.Slf4j;

import java.io.File;

@Slf4j
public class PcVersionUtils {

    /**
     *
     * 获取PC客户端的最新版本
     * zhaoman
     * 2021-08-06
     *
     * @return
     */
    public static String getPcStartLatestVersion(String host){
        return HttpUtil.get(host+"/cinorecycle/sys_configuration/get-pc-client-version");
    }


    public static void download(String host , String pwdPath,String latestVersion){
        log.info("当前正在卸载原来版本......");
        FileUtil.del(pwdPath+"/p.jar");
        log.info("卸载原来版本成功！");
        log.info("当前正在更新版本......");
        String fileUrl = host+"/cinorecycle/download/download-pc-start/"+latestVersion;
        String fileUrl2 = host+"/cinorecycle/download/download-pc-start/p.jar";
        try {
            HttpUtil.downloadFile(fileUrl, FileUtil.file(pwdPath));
            HttpUtil.downloadFile(fileUrl2, FileUtil.file(pwdPath));
            log.info("更新版本成功！");
        } catch (Exception e) {
            log.error("更新版本失败！");
            log.error(e.getMessage());
        }

    }


    /**
     *
     * PC客户端是否是最新的版本
     * zhaoman
     * 2021-08-06
     *
     * @return
     */
    public static boolean isLatestVersion(String pwdPath, String latestVersion){
        boolean flag = false;

        File[] files = FileUtil.ls(pwdPath);
        if(files==null || files.length==0){
            log.error("当前路径没有文件或者文件夹");
            return flag;
        }



        for (File file : files) {
//            遍历所有的文件
            if(file.isFile()){
                String fileName = file.getName();
                if(fileName.equals(latestVersion)){
                    flag = true;
                    break;
                }
            }
        }
        return flag;
    }

}
